package com.jzg.jcptadmin.presenter;

import android.content.Context;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.SubmitValueVerification;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BasePresenter;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.VinDetails;
import com.jzg.jcptadmin.data.vo.Vindata;
import com.jzg.jcptadmin.viewinterface.QueryVinFragmentInterface;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by wangyd on 15/12/28.
 */
public class QueryVinPresenter extends BasePresenter<QueryVinFragmentInterface> {
    private final DataManager mDataManager;
    private Subscription mSubscription;
    private QueryVinFragmentInterface mView;

    private List<String> vinHistory;
    private AppContext appContext;
    private Vindata vindata;

    public QueryVinPresenter(DataManager dataManager, AppContext appContext) {
        mDataManager = dataManager;
        vinHistory = new ArrayList<>();
        this.appContext = appContext;
    }

    @Override
    public void attachView(QueryVinFragmentInterface mvpView) {
        super.attachView(mvpView);
        this.mView = mvpView;
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mSubscription != null) mSubscription.unsubscribe();
    }

    /**
     * 根据vin码查询
     */
    public void queryVin(Context context) {
        checkViewAttached();
        if (!AppContext.isNetWork) return;
        final Map<String, String> params = mView.getQueryVinParams();
        if (SubmitValueVerification.isEmpty(params)) {
            mView.showError(context.getResources().getString(R.string.params_exception));
            return;
        }

        mSubscription = mDataManager.loadVinResult(params).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<VinDetails>() {
            @Override
            public void onCompleted() {
//                vinHistory.setVin(params.get("vin"));
//                VinList.vins.add(vinHistory);
                Logger.i("vin is " + params.get("vin"));
                //  vinHistory.add(params.get("vin"));
                vinHistory.add(exChange(params.get("vin")));

            }

            @Override
            public void onError(Throwable e) {
                if (e != null&& mView!=null) {
                    mView.showError(e.toString());
                }
            }

            @Override
            public void onNext(VinDetails vinDetails) {
//                Logger.i(vinDetails.getStatus() + "");
                mView.toVinResultActivity(vinDetails);
            }
        });
    }

    public List<String> getVinHistory() {
        if (vinHistory.size() == 0) {
            vindata = (Vindata) ACache.get(appContext).getAsObject("Vindata");
            if (vindata != null) {
                vinHistory = vindata.getShowVins();
            }

        }
        return vinHistory;
    }

    public void SaveList(List<String> list) {
        if (vindata == null) {
            vindata = new Vindata();
        }
        vindata.setShowVins(list);
        ACache.get(appContext).put("Vindata", vindata);

    }

    /**
     * 重新排序历史vin查询并去重
     *
     * @param vins
     * @return
     */
    public List<String> sortVins(List<String> vins) {
        final List<String> showVins = new ArrayList<>();
        mSubscription = Observable.from(vins).distinct().takeLast(5).subscribe(new Observer<String>() {
            @Override
            public void onCompleted() {
                Collections.reverse(showVins);

            }

            @Override
            public void onError(Throwable e) {
                if (e != null)
                    mView.showError(e.toString());
            }

            @Override
            public void onNext(String s) {
                Logger.i("distinct is " + s);
                showVins.add(s);
            }
        });
        return showVins;
    }


    //把小写转成大写
    public static String exChange(String str) {
        StringBuffer sb = new StringBuffer();
        if (str != null) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (Character.isUpperCase(c)) {
                    sb.append(c);
                } else if (Character.isLowerCase(c)) {
                    sb.append(Character.toUpperCase(c));
                } else {
                    sb.append(c);
                }
            }
        }

        return sb.toString();
    }
}
